from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.db.models import Q
from .models import Book, BorrowRecord
from datetime import datetime, timedelta
from django.http import HttpResponse
from import_export import resources
from tablib import Dataset
from io import BytesIO
import time
from django.contrib.auth import logout
from django.shortcuts import redirect
from django.contrib import messages
from django.contrib.auth import logout, authenticate, login
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login, authenticate
from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate
from .forms import RegisterForm  # 导入我们刚创建的注册表单

def register(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            return redirect('books:book_list')
    else:
        form = RegisterForm()
    return render(request, 'registration/register.html', {'form': form})

def import_export(request):
    return render(request, 'books/import_export.html')
# 自定义登录视图
def custom_login(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            return redirect('books:book_list')
        else:
            messages.error(request, '用户名或密码错误')
    return render(request, 'registration/login.html')  # 使用你的前端登录模板

def custom_logout(request):
    logout(request)
    return redirect('books:custom_login')  # 退出后跳转到自定义登录页


class BookResource(resources.ModelResource):
    class Meta:
        model = Book


class BorrowRecordResource(resources.ModelResource):
    class Meta:
        model = BorrowRecord


def export_books(request):
    format = request.GET.get('format', 'xlsx')
    book_resource = BookResource()
    dataset = book_resource.export()

    if format == 'csv':
        response = HttpResponse(dataset.csv, content_type='text/csv')
        response['Content-Disposition'] = f'attachment; filename=books_{time.strftime("%Y%m%d")}.csv'
    else:
        response = HttpResponse(content_type='application/vnd.ms-excel')
        response['Content-Disposition'] = f'attachment; filename=books_{time.strftime("%Y%m%d")}.xlsx'
        dataset.xlsx = dataset.export('xlsx')
        response.write(dataset.xlsx)

    return response


def export_records(request):
    format = request.GET.get('format', 'xlsx')
    record_resource = BorrowRecordResource()
    dataset = record_resource.export()

    if format == 'csv':
        response = HttpResponse(dataset.csv, content_type='text/csv')
        response['Content-Disposition'] = f'attachment; filename=records_{time.strftime("%Y%m%d")}.csv'
    else:
        response = HttpResponse(content_type='application/vnd.ms-excel')
        response['Content-Disposition'] = f'attachment; filename=records_{time.strftime("%Y%m%d")}.xlsx'
        dataset.xlsx = dataset.export('xlsx')
        response.write(dataset.xlsx)

    return response


def import_data(request):
    if request.method == 'POST':
        import_type = request.POST.get('import_type')
        file = request.FILES['file']

        try:
            print(f"尝试导入文件: {file.name}, 类型: {import_type}")

            if import_type == 'books':
                resource = BookResource()
            else:
                resource = BorrowRecordResource()

            dataset = Dataset()
            file_content = file.read()
            print(f"文件头: {file_content[:100]}")

            file.seek(0)

            if file.name.endswith('.xlsx'):
                imported_data = dataset.load(file_content, format='xlsx')
            elif file.name.endswith('.csv'):
                imported_data = dataset.load(file_content.decode('utf-8'), format='csv')
            else:
                messages.error(request, '不支持的文件格式')
                return redirect('books:import_export')
            print(f"加载的数据前3行: {imported_data[:3]}")

            result = resource.import_data(dataset, dry_run=True)

            if result.has_errors():
                error_messages = []
                for row_num, errors in result.row_errors():
                    for error in errors:
                        error_messages.append(f"行 {row_num}: {error.error}")
                messages.error(request, '导入错误: ' + '; '.join(error_messages))
            else:
                # 实际导入
                resource.import_data(dataset, dry_run=False)
                # 获取实际导入数量
                imported_count = len(result.valid_rows())
                messages.success(request, f'成功导入 {imported_count} 条记录')
                # 打印导入结果
                print(f"成功导入 {imported_count} 条{import_type}记录")
        except Exception as e:
            error_msg = f'导入失败: {str(e)}'
            messages.error(request, error_msg)
            # 打印完整错误信息到控制台
            import traceback
            traceback.print_exc()
        return redirect('books:import_export')

    return redirect('books:import_export')


def book_list(request):
    books = Book.objects.all()
    return render(request, 'books/book_list.html', {'books': books})


def book_detail(request, pk):
    book = get_object_or_404(Book, pk=pk)
    is_borrowed = False
    if request.user.is_authenticated:
        is_borrowed = BorrowRecord.objects.filter(book=book, borrower=request.user, is_returned=False).exists()
    return render(request, 'books/book_detail.html', {'book': book, 'is_borrowed': is_borrowed})


@login_required
def borrow_book(request, pk):
    book = get_object_or_404(Book, pk=pk)
    if book.status != 'available':
        messages.warning(request, '该书当前不可借阅')
        return redirect('books:book_detail', pk=pk)

    if BorrowRecord.objects.filter(book=book, borrower=request.user, is_returned=False).exists():
        messages.warning(request, '您已经借阅了该书')
        return redirect('books:book_detail', pk=pk)

    # 借阅期限为30天
    due_date = datetime.now() + timedelta(days=30)
    BorrowRecord.objects.create(
        book=book,
        borrower=request.user,
        due_date=due_date
    )
    book.status = 'borrowed'
    book.save()
    messages.success(request, '借阅成功')
    return redirect('books:book_detail', pk=pk)


@login_required
def return_book(request, pk):
    book = get_object_or_404(Book, pk=pk)
    record = BorrowRecord.objects.filter(book=book, borrower=request.user, is_returned=False).first()

    if not record:
        messages.warning(request, '您没有借阅该书')
        return redirect('books:book_detail', pk=pk)

    record.is_returned = True
    record.return_date = datetime.now()
    record.save()

    book.status = 'available'
    book.save()
    messages.success(request, '归还成功')
    return redirect('books:book_detail', pk=pk)


def search_books(request):
    query = request.GET.get('q')
    if query:
        books = Book.objects.filter(
            Q(title__icontains=query) |
            Q(author__icontains=query) |
            Q(isbn__icontains=query)
        )
    else:
        books = Book.objects.all()
    return render(request, 'books/search_results.html', {'books': books, 'query': query})


@login_required
def my_books(request):
    records = BorrowRecord.objects.filter(borrower=request.user, is_returned=False)
    return render(request, 'books/my_books.html', {'records': records})
